package com.share.im.manager;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.ReportedData;
import org.jivesoftware.smackx.ReportedData.Row;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.smackx.search.UserSearchManager;

import android.content.Context;

import com.share.im.manager.ContacterManager.MRosterGroup;
import com.share.im.model.User;
import com.share.im.model.UserBean;
import com.share.im.util.common.StringUtil;

public class UserManager {
	private static UserManager userManager = null;

	private UserManager() {

	}

	public static UserManager getInstance(Context context) {

		if (userManager == null) {
			userManager = new UserManager();
		}

		return userManager;
	}

	/**
	 * 
	 * 获取用户的vcard信息 .
	 * 
	 * @return
	 */
	public VCard getUserVCard(String jid) {
		XMPPConnection xmppConn = XmppConnectionManager.getInstance()
				.getConnection();
		VCard vcard = new VCard();
		try {
			vcard.load(xmppConn, jid);
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		return vcard;
	}

	/**
	 * 
	 * 保存用户的vcard信息. 注：修改vcard时，头像会丢失，此处为asmack.jar的bug，目前还无法修复
	 * 
	 * @param vCard
	 * @return
	 */
	public VCard saveUserVCard(VCard vCard) {
		XMPPConnection xmppConn = XmppConnectionManager.getInstance()
				.getConnection();
		try {
			vCard.save(xmppConn);
			return getUserVCard(vCard.getJabberId());
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 获取用户头像信息 .
	 * 
	 * @param connection
	 * @param jid
	 * @return
	 */
	public InputStream getUserImage(String jid) {
		XMPPConnection connection = XmppConnectionManager.getInstance()
				.getConnection();
		InputStream ic = null;
		try {
			System.out.println("获取用户头像信息: " + jid);
			VCard vcard = new VCard();
			vcard.load(connection, jid);

			if (vcard == null || vcard.getAvatar() == null) {
				return null;
			}
			ByteArrayInputStream bais = new ByteArrayInputStream(
					vcard.getAvatar());
			return bais;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ic;
	}
	
	/**
	 * 查找用户
	 */
	public List<UserBean> searchUsers(String userName,List<MRosterGroup> rGroups) throws XMPPException
	{
		String urlStr = "search."+XmppConnectionManager.getInstance().getConnection().getServiceName();
		System.out.println("~~~~~~"+urlStr);
		List<UserBean> results = new ArrayList<UserBean>();
		// System.out.println("查询开始..............."+connection.getHost()+connection.getServiceName());

		UserSearchManager usm = new UserSearchManager(XmppConnectionManager.getInstance().getConnection());

		Form searchForm = usm.getSearchForm(urlStr);
		Form answerForm = searchForm.createAnswerForm();
		answerForm.setAnswer("Username", true);
		answerForm.setAnswer("search", userName);
		ReportedData data = usm.getSearchResults(answerForm, urlStr);
		Iterator<Row> it = data.getRows();
		Row row = null;
		UserBean user = null;
		while (it.hasNext())
		{
			user = new UserBean();
			row = it.next();
			String curUserName = row.getValues("Username").next().toString();// 当前用户名
			user.setUserName(curUserName);
			user.setName(row.getValues("Name").next().toString());
			user.setEmail(row.getValues("Email").next().toString());
			System.out.println(row.getValues("Username").next());
			System.out.println(row.getValues("Name").next());
			System.out.println(row.getValues("Email").next());
			
			user.setStatus(isExitJid(StringUtil.getJidByName(curUserName), rGroups)?1:0);
			
			results.add(user);
			// 若存在，则有返回,UserName一定非空，其他两个若是有设，一定非空
		}

		return results;
	}
	
	/**
	 * 添加好友
	 */
	public void addUser(String userName,String nickname_in){
		try
		{
			XmppConnectionManager.getInstance().getConnection().getRoster().createEntry(StringUtil.getJidByName(userName), nickname_in, null);
		}
		catch (XMPPException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断用户名是否存在
	 * 
	 * @param userName
	 * @param groups
	 * @return
	 */
	protected boolean isExitJid(String userJid, List<MRosterGroup> groups) {
		for (MRosterGroup g : groups) {
			List<User> users = g.getUsers();
			if (users != null && users.size() > 0) {
				for (User u : users) {
					if (u.getJID().equals(userJid)) {
						return true;
					}
				}
			}
		}

		return false;
	}
}
